package com.shortlink.common.util;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * url工具类
 *
 * @author wp
 */
public class UrlUtils {
    /**
     * 正则表达式用于验证域名
     */
    private static final String DOMAIN_REGEX = "^(?!-)([A-Za-z0-9-]{1,63}(?<!-)(\\.[A-Za-z]{2,})+)$";
    private static final Pattern DOMAIN_PATTERN = Pattern.compile(DOMAIN_REGEX);
    /**
     * 正则表达式用于验证 Base62 字符串
     */
    private static final String BASE62_REGEX = "^[A-Za-z0-9]+$";

    /**
     * 校验域名是否有效
     */
    public static boolean isValidDomain(String domain) {
        if ("localhost".equals(domain)) {
            return true;
        }
        return domain != null && DOMAIN_PATTERN.matcher(domain).matches();
    }

    /**
     * 校验shortUri是否有效
     */
    public static boolean isValidShortUri(String shortUri) {
        return shortUri != null && shortUri.matches(BASE62_REGEX);
    }

    /**
     * 拼接短链接
     */
    public static String concatShortUrl(String domain, String shortUrl) {
        return domain + "/" + shortUrl;
    }

    /**
     * 获取原始链接中的域名
     */
    public static String extractDomain(String url) {
        String domain = null;
        try {
            URI uri = new URI(url);
            String host = uri.getHost();
            if (StrUtil.isNotBlank(host)) {
                domain = host;
                if (domain.startsWith("www.")) {
                    domain = host.substring(4);
                }
            }
        } catch (Exception ignored) {
        }
        return domain;
    }

    /**
     * 获取url图标
     */
    @SneakyThrows
    public static String getFavicon(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK == responseCode) {
            Document document = Jsoup.connect(url).get();
            Element faviconLink = document.select("link[rel~=(?i)^(shortcut )?icon]").first();
            if (faviconLink != null) {
                return faviconLink.attr("abs:href");
            }
        }
        return null;
    }

    /**
     * 获取url标题
     */
    @SneakyThrows
    public static String getTitleByUrl(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Document document = Jsoup.connect(url).get();
            return document.title();
        }
        return "Error while fetching title.";
    }
}
